<template>
  <div class="detail-page">
    <div class="detail-header">
      <router-link to="/" class="back-link">&lt; 返回工作台</router-link>
      <h2>申请详情</h2>
    </div>

    <!-- 错误提示 -->
    <div v-if="store.error" class="error-message">
      {{ store.error }}
      <button @click="store.clearError()" class="close-btn">×</button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 申请详情内容 -->
    <div v-else-if="application" class="detail-layout">
      <ApprovalProgress :status="application.status" />
      <ApplicationInfo :application="application" />
      <ApprovalHistory :application="application" />

      <!-- 审批操作（仅审批人员可见） -->
      <ApprovalActions v-if="canTakeAction" :application="application" />

      <!-- 被驳回申请的操作按钮 -->
      <div v-if="application?.status === 'REJECTED'" class="rejected-actions">
        <el-button type="warning" @click="showEditDialog = true" :icon="EditPen">
          编辑申请
        </el-button>
        <el-button type="success" @click="handleResubmit" :icon="Refresh"> 重新提交 </el-button>
        <el-button type="danger" @click="showCancelDialog = true" :icon="Close">
          撤销申请
        </el-button>
      </div>

      <!-- 重新提交按钮（仅被驳回的申请且是申请人可见） -->
      <div v-if="canResubmit" class="resubmit-section">
        <h3>重新提交申请</h3>
        <p class="resubmit-tip">您的申请已被驳回，可以根据驳回意见修改后重新提交。</p>
        <button @click="handleResubmit" class="btn-resubmit" :disabled="store.loading">
          {{ store.loading ? '重新提交中...' : '重新提交申请' }}
        </button>
      </div>

      <!-- 撤销确认对话框 -->
      <el-dialog
        v-model="showCancelDialog"
        title="撤销申请"
        width="600px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <CancelApplication
          v-if="application"
          :application="application"
          @cancel="handleCancelCancel"
          @success="handleCancelSuccess"
        />
      </el-dialog>

      <!-- 编辑申请对话框 -->
      <el-dialog
        v-model="showEditDialog"
        title="编辑申请"
        width="800px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <EditableApplicationForm
          v-if="application"
          :application="application"
          @cancel="handleEditCancel"
          @success="handleEditSuccess"
        />
      </el-dialog>
    </div>

    <!-- 申请未找到 -->
    <div v-else class="not-found">
      <h3>申请单未找到</h3>
      <p>您要查看的申请单不存在或已被删除。</p>
      <router-link to="/" class="btn-back">返回工作台</router-link>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { EditPen, Refresh, Close } from '@element-plus/icons-vue'
import { useApplicationStore } from '@/store/application'
import ApplicationInfo from '@/components/ApplicationInfo.vue'
import ApprovalProgress from '@/components/ApprovalProgress.vue'
import ApprovalHistory from '@/components/ApprovalHistory.vue'
import ApprovalActions from '@/components/ApprovalActions.vue'
import CancelApplication from '@/components/CancelApplication.vue'
import EditableApplicationForm from '@/components/EditableApplicationForm.vue'

const props = defineProps<{ id: string }>()
const store = useApplicationStore()

// 申请详情
const application = computed(() => store.applications.find((app) => app.id === props.id))
const loading = computed(() => store.loading)

// 是否可以执行审批操作
const canTakeAction = computed(() => {
  if (!application.value) return false
  const { status } = application.value
  const { role } = store.currentUser

  if (status === 'PENDING_HEAD_REVIEW' && role === 'head') return true
  if (status === 'PENDING_FINANCE_REVIEW' && role === 'finance') return true
  if (status === 'PENDING_GM_REVIEW' && role === 'gm') return true
  return false
})

// 是否可以重新提交
const canResubmit = computed(() => {
  if (!application.value) return false
  return (
    application.value.status === 'REJECTED' &&
    application.value.applicantId === store.currentUser.id
  )
})

// 重新提交申请
const handleResubmit = async () => {
  if (!application.value) return

  try {
    await store.resubmitApplication(application.value.id)
    alert('申请重新提交成功！已进入部门主管审批流程。')
  } catch (error: unknown) {
    alert(`重新提交失败：${error instanceof Error ? error.message : '未知错误'}`)
  }
}

// 组件挂载时加载数据
onMounted(async () => {
  if (store.applications.length === 0) {
    await store.fetchApplications()
  }
})

// 撤销确认对话框
const showCancelDialog = ref(false)

// 编辑申请对话框
const showEditDialog = ref(false)

// 处理编辑申请
const handleEditCancel = () => {
  showEditDialog.value = false
}

const handleEditSuccess = () => {
  showEditDialog.value = false
  // 重新获取申请数据
  store.fetchApplications()
}

// 处理撤销申请
const handleCancelCancel = () => {
  showCancelDialog.value = false
}

const handleCancelSuccess = () => {
  showCancelDialog.value = false
  // 重新获取申请数据
  store.fetchApplications()
  ElMessage({
    type: 'success',
    message: '申请撤销成功！',
    duration: 3000,
  })
}
</script>

<style scoped>
.detail-page {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.back-link {
  color: #3498db;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.back-link:hover {
  color: #2980b9;
}

.detail-header h2 {
  margin: 0;
  color: #333;
}

.error-message {
  background: #e74c3c;
  color: white;
  padding: 12px 16px;
  border-radius: 6px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 18px;
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
}

.loading {
  text-align: center;
  padding: 50px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.detail-layout {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.resubmit-section {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
}

.resubmit-section h3 {
  margin: 0 0 10px 0;
  color: #856404;
}

.resubmit-tip {
  margin: 0 0 15px 0;
  color: #856404;
  font-size: 14px;
}

.btn-resubmit {
  background-color: #f39c12;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.btn-resubmit:hover:not(:disabled) {
  background-color: #e67e22;
}

.btn-resubmit:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.not-found {
  text-align: center;
  padding: 50px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.not-found h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.not-found p {
  margin: 0 0 20px 0;
  color: #666;
}

.btn-back {
  display: inline-block;
  background-color: #3498db;
  color: white;
  text-decoration: none;
  padding: 10px 20px;
  border-radius: 6px;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.btn-back:hover {
  background-color: #2980b9;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-page {
    padding: 10px;
  }

  .detail-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .detail-header h2 {
    font-size: 20px;
  }
}

/* 被驳回申请的操作按钮样式 */
.rejected-actions {
  margin-top: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #fff5f5 0%, #fef2f2 100%);
  border: 1px solid #fecaca;
  border-radius: 12px;
  text-align: center;
}

.rejected-actions .el-button {
  margin: 0 8px;
  border-radius: 8px;
  font-weight: 500;
  padding: 12px 24px;
}

.rejected-actions .el-button--warning {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  border: none;
}

.rejected-actions .el-button--warning:hover {
  background: linear-gradient(135deg, #d97706 0%, #b45309 100%);
}

.rejected-actions .el-button--success {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border: none;
}

.rejected-actions .el-button--success:hover {
  background: linear-gradient(135deg, #059669 0%, #047857 100%);
}

.rejected-actions .el-button--danger {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  border: none;
}

.rejected-actions .el-button--danger:hover {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
}
</style>
